package com.linkoog.devtools.archive.action;

import com.intellij.ide.highlighter.ArchiveFileType;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.linkoog.devtools.archive.filesystem.gz.GZFileType;
import com.linkoog.devtools.archive.filesystem.sevenzip.SevenZipFileType;
import com.linkoog.devtools.archive.filesystem.tar.TarFileType;
import com.linkoog.devtools.archive.filesystem.tar.TarGzFileType;
import com.linkoog.devtools.archive.filesystem.zip.ArchiveFileTypeExt;
import com.linkoog.devtools.archive.util.CompressionFileUtil;
import com.linkoog.devtools.archive.util.FileNameUtil;
import com.linkoog.devtools.archive.util.SelectedItemsUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UnZipArchiveAction extends AnAction implements DumbAware {



    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        final Project project = event.getProject();
        if (project == null) return;

        List<VirtualFile> selectedFiles = SelectedItemsUtil.getSelectedItems(event);
        if (selectedFiles.isEmpty()) return;

        ArrayList<VirtualFile> files = new ArrayList<>();
        for (VirtualFile selectedFile : selectedFiles) {
            if (selectedFile == null || selectedFile.isDirectory()) continue;
            if (! selectedFile.isInLocalFileSystem()) continue;

            FileType fileType = selectedFile.getFileType();
            if (fileType.equals(ArchiveFileType.INSTANCE) || fileType.equals(ArchiveFileTypeExt.INSTANCE)) {
                files.add(selectedFile);
            } else if (fileType.equals(GZFileType.INSTANCE) || fileType.equals(TarGzFileType.INSTANCE)) {
                files.add(selectedFile);
            } else if (fileType.equals(TarFileType.INSTANCE)) {
                files.add(selectedFile);
            } else if (fileType.equals(SevenZipFileType.INSTANCE)) {
                files.add(selectedFile);
            }
        }

        if (files.isEmpty()) return;

        unzip(project, files);
    }

    private void unzip(final Project project,  final ArrayList<VirtualFile> files) {
        ApplicationManager.getApplication().executeOnPooledThread(() -> {
            ProgressManager.getInstance().run(new Task.Backgroundable(project, "Unzipping files", true) {
                @Override
                public void run(@NotNull ProgressIndicator progressIndicator) {
                    progressIndicator.setText("Unzipping task start...");
                    long startTime = System.currentTimeMillis();
                    for (VirtualFile file : files) {
                        progressIndicator.setText("Unzipping:  " + file.getName());

                        FileType fileType = file.getFileType();
                        if (fileType.equals(ArchiveFileType.INSTANCE) || fileType.equals(ArchiveFileTypeExt.INSTANCE)){
                            //upzip
                            String filePath = file.getCanonicalPath();
                            if (filePath != null){
                                File unzipFile = new File(filePath);
                                try {
                                    doUnzip(unzipFile);
                                } catch (IOException ignored) {
                                }
                            }
                        } else if (fileType.equals(GZFileType.INSTANCE)) {
                            //GZFileType.unzip(file);
                        } else if (fileType.equals(TarGzFileType.INSTANCE)) {
                            //TarGzFileType.unzip(file);
                        } else if (fileType.equals(TarFileType.INSTANCE)) {
                            //TarFileType.unzip(file);
                        } else if (fileType.equals(SevenZipFileType.INSTANCE)) {
                            //SevenZipFileType.unzip(file);
                        }

                    }

                    // 刷新文件树
                    ProjectView.getInstance(project).refresh();
                    // 刷新虚拟文件系统的缓存
                    VirtualFileManager.getInstance().asyncRefresh(null);
                    progressIndicator.setText("Unzipping task complete, cost time: " + (System.currentTimeMillis() - startTime) + "ms");
                }
            });
        });
    }

    private void doUnzip(File unzipFile) throws IOException {
        File parentFile = unzipFile.getParentFile();
        File targetFile = new File(parentFile, FileNameUtil.getFileNameWithoutExtension(unzipFile));
        targetFile.mkdirs();

        CompressionFileUtil.zipUnCompress(unzipFile.getAbsolutePath(), targetFile.getAbsolutePath());
    }



}
